<template>
  <div id="mapContainer">
    <div id="amap" ref="amap"></div>
  </div>
</template>

<script>
import Loading from '@/components/loading';
const MARKER_MOVE_SPEED = 75;
export default {
  name: 'taxi-map',
  data() {
    return {
      instance: null,
      geolocation: null,
      picker: null,
      dingweiMarkder: null,
      dingweiIcon: new AMap.Icon({
        size: new AMap.Size(36, 46),
        image: require('@/assets/imgs/dw_icon.png'),
        imageSize: new AMap.Size(18, 23)
      }),
      currentRoutes: null,
      driveCar: null,
      drivePath: null,
      driveCarInfo: {
        timeStr: '',
        mileStr: '',
        milePreStr: '距终点'
      },
      driveDistance: 0
    };
  },
  props: {
    center: {
      type: Array,
      default: () => {
        return [116.397428, 39.90923];
      }
    },
    zoom: {
      type: Number,
      default: 11
    },
    noAutoZoom: {
      type: Boolean,
      default: false
    }
  },
  mounted() {
    Loading.show();
    let c = this.center;
    let z = this.zoom;
    this.instance = new AMap.Map(this.$refs.amap, {
      zoom: z, // 级别
      center: c, // 中心点坐标
      mapStyle: 'amap://styles/b7bb350207a4d6e98610556cbaa8d41b'
    });
    this.instance.on('complete', evt => {
      console.log('出租车地图加载完成');
      this.$emit('complete', this.instance);
      Loading.hide();
      if (process.env.NODE_ENV === 'development') {
        AMap.plugin(['AMap.ToolBar'], () => {
          let toolbar = new AMap.ToolBar();
          this.instance.addControl(toolbar);
        });
      }
    });
    this.instance.on('dragstart', evt => {
      this.$emit('dragstart');
    });
  },
  methods: {
    initPositionPicker() {
      if (this.picker) {
        return;
      }
      // 加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
      AMapUI.loadUI(['misc/PositionPicker'], PositionPicker => {
        this.picker = new PositionPicker({
          mode: 'dragMap', // 设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
          map: this.instance, // 依赖地图对象
          iconStyle: {
            // 自定义外观
            url: require('@/assets/imgs/sc_datouzhen.png'), // 图片地址
            size: [25, 36], // 要显示的点大小，将缩放图片
            ancher: [12.5, 36] // 锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
          }
        });
        this.picker.on('success', this.onPickerSelect);
        this.picker.start();
      });
    },
    stopPositionPicker() {
      if (this.picker) {
        this.picker.stop();
        this.picker.off('sucess', this.onPickerSelect);
        this.picker = null;
      }
    },
    onPickerSelect(positionResult) {
      let result = {
        coordinate: [],
        stationName: '',
        position: '',
        adcode: ''
      };
      result.coordinate = [positionResult.position.lng, positionResult.position.lat];
      if (positionResult.regeocode.pois.length > 0) {
        result.stationName = positionResult.regeocode.pois[0].name;
      } else {
        result.stationName = positionResult.regeocode.formattedAddress;
      }
      if (positionResult.regeocode.addressComponent) {
        result.adcode = positionResult.regeocode.addressComponent.adcode;
      }
      result.position = positionResult.address;
      this.$emit('select', result);
    },
    initCenter(center) {
      if (this.instance) {
        this.instance.setCenter(center);
        this.instance.setZoom(16);
        if (this.dingweiMarkder) {
          this.instance.remove(this.dingweiMarkder);
          this.dingweiMarkder = null;
          this.dingweiMarkder = new AMap.Marker({
            position: center,
            icon: this.dingweiIcon,
            offset: new AMap.Pixel(-8, -12)
          });
          this.instance.add(this.dingweiMarkder);
        } else {
          this.dingweiMarkder = new AMap.Marker({
            position: center,
            icon: this.dingweiIcon,
            offset: new AMap.Pixel(-8, -12)
          });
          this.instance.add(this.dingweiMarkder);
        }
      }
    },
    setCenter(center) {
      if (this.instance) {
        this.instance.setCenter(center);
      }
    },
    showStartEndPosition(start, end, path = false, hasTip = false) {
      this.addStartMarker(start.start_lnglat.split(','), start.start_pst);
      this.addEndMarker(end.end_lnglat.split(','), end.end_pst);
      if (path) {
        this.createDrivingRoute(start.start_lnglat.split(','), end.end_lnglat.split(',')).then(res => {
          if (hasTip) {
            let dis = res.distance / 1000;
            this.createTextTip(end.end_lnglat.split(','), dis.toFixed(1), '3');
          }
          this.updateDrivedPath();
        });
      }
      this.instance.setFitView();
    },
    addStartMarker(lnglat, name = '') {
      // 添加一个起点marker对象
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: require('@/assets/imgs/snyc_shangche_icon.png'),
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-10, -24),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-location-name">' + name + '</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(0, 15)
        });
        this.instance.add(textMarker);
      }
    },
    addEndMarker(lnglat, name = '') {
      // 添加一个终点marker对象
      if (this.instance) {
        let icon = new AMap.Icon({
          size: new AMap.Size(40, 48), // 图标尺寸
          image: require('@/assets/imgs/snyc_xiache_icon.png'),
          imageSize: new AMap.Size(20, 24) // 根据所设置的大小拉伸或压缩图片
        });
        let marker = new AMap.Marker({
          position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          offset: new AMap.Pixel(-10, -24),
          icon: icon
        });
        this.instance.add(marker);
        let textMarker = new AMap.Text({
          position: lnglat,
          text: '<div class="map-location-name">' + name + '</div>',
          style: {
            border: '0px',
            background: 'transparent',
            height: '35px'
          },
          offset: new AMap.Pixel(0, 15)
        });
        this.instance.add(textMarker);
      }
    },
    updateDriveCar(position) {
      if (this.driveCar) {
        this.driveCar.moveTo(position, MARKER_MOVE_SPEED);
      } else {
        this.driveCar = new AMap.Marker({
          map: this.instance,
          position: position,
          offset: new AMap.Pixel(-18, -9),
          angle: -90,
          autoRotation: true,
          icon: new AMap.Icon({
            size: new AMap.Size(72, 36), // 图标尺寸
            image: process.env.BASE_URL + 'static/imgs/car@2x.png',
            imageSize: new AMap.Size(36, 18) // 根据所设置的大小拉伸或压缩图片
          })
        });
      }
      if (this.driveCarText) {
        this.driveCarText.moveTo(position, MARKER_MOVE_SPEED);
      }
    },
    createTextTip(position, text, style) {
      let str = '<div class="map-shareorder-infowindow">' + text + '</div>';
      if (style === '0') {
        // 普通文字
        str = '<div class="map-shareorder-infowindow">' + text + '</div>';
      } else if (style === '1') {
        // 司机接驾提示文字
        str =
          '<div class="map-shareorder-infowindow">距您<span style="color:#FF6917">' +
          this.driveCarInfo.mileStr +
          '</span> 预计行驶<span style="color:#FF6917">' +
          this.driveCarInfo.timeStr +
          '</span></div>';
      } else if (style === '2') {
        // 行程中提示文字
        str =
          '<div class="map-shareorder-infowindow">距终点<span style="color:#FF6917">' +
          this.driveCarInfo.mileStr +
          '</span> 预计行驶<span style="color:#FF6917">' +
          this.driveCarInfo.timeStr +
          '</span></div>';
      } else if (style === '3') {
        // 共行驶X公里
        str = '<div class="map-shareorder-infowindow">共行驶<span style="color:#FF6917">' + text + '公里</span></div>';
      }
      this.driveCarText = new AMap.Text({
        map: this.instance,
        bubble: false,
        text: str,
        position: position,
        textAlign: 'center',
        verticalAlign: 'middle',
        style: {
          border: '0px',
          background: 'transparent',
          height: '35px'
        },
        clickable: false,
        offset: new AMap.Pixel(0, -40)
      });
    },
    createPathNavigator(start, dest) {
      return new Promise((resolve, reject) => {
        this.createDrivingRoute(start, dest)
          .then(result => {
            console.log(result);
            let timeLeftMin = result.time / 60;
            let timeLeftStr = timeLeftMin.toFixed(0) + '分钟';
            let mileLeftMeter = result.distance / 1000;
            let mileLeftStr = mileLeftMeter.toFixed(1) + '公里';
            this.driveCarInfo = {
              timeStr: timeLeftStr,
              mileStr: mileLeftStr
            };
            this.updateDrivePath();
            resolve();
          })
          .catch(reason => {
            reject(reason);
          });
      });
    },
    createDrivingRoute(start, dest) {
      return new Promise((resolve, reject) => {
        if (this.instance) {
          AMap.plugin('AMap.Driving', () => {
            let result = null;
            let driving = new AMap.Driving({
              // map: this.mapInstance,
              hideMarkers: true,
              autoFitView: false,
              showTraffic: false,
              isOutline: false,
              policy: AMap.DrivingPolicy.REAL_TRAFFIC
            });
            driving.search(start, dest, (status, data) => {
              if (data.routes) {
                if (data.routes.length > 0) {
                  this.currentRoutes = [];
                  result = data.routes[0];
                  result.steps.forEach(item => {
                    item.path.forEach(item => {
                      this.currentRoutes.push(item);
                    });
                  });
                  resolve(result);
                } else {
                  reject(new Error('线路规划失败' + data));
                }
              } else {
                reject(new Error('线路规划失败' + data));
              }
            });
          });
        } else {
          reject(new Error('地图还没有初始化，无法使用实时导航功能'));
        }
      });
    },
    updateDrivePath() {
      if (this.drivePath) {
        this.drivePath.setPath(this.currentRoutes);
      } else {
        this.drivePath = new AMap.Polyline({
          map: this.instance,
          path: this.currentRoutes,
          strokeWeight: 5,
          strokeColor: '#0AA436'
        });
      }
    },
    updateDrivedPath() {
      let color = '#BFBFBF';
      if (this.drivePath) {
        this.drivePath.setPath(this.currentRoutes);
      } else {
        this.drivePath = new AMap.Polyline({
          map: this.instance,
          path: this.currentRoutes,
          strokeWeight: 5,
          strokeColor: color
        });
      }
    },
    removePathNavigator() {
      if (this.driveCar) {
        this.driveCar.stopMove();
        this.instance.remove(this.driveCar);
        this.driveCar = null;
      }
      if (this.drivePath) {
        this.instance.remove(this.drivePath);
        this.drivePath = null;
      }
    },
    clearMap() {
      if (this.instance) {
        this.instance.clearMap();
        this.removePathNavigator();
      }
    },
    setFitView() {
      if (this.instance) {
        this.instance.setFitView();
      }
    }
  }
};
</script>

<style lang="stylus">
#mapContainer {
  width: 100vw;
  height: 100vh;

  #amap {
    width: 100%;
    height: 100%;
  }
}

.map-shareorder-infowindow {
  position: relative;
  border-radius: 10px;
  padding: 10px 15px;
  box-shadow: 0 2px 6px 0 #999;
  border-radius: 40px;
  background-color: #fff;
  font-size: 24px;
  color: #4A4A4A;
  text-align: center;
  white-space: nowrap;
}

.map-shareorder-infowindow:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 0;
  border: 20px solid transparent;
  border-top-color: #fff;
  border-bottom: 0;
  margin-left: -10px;
  margin-bottom: -10px;
}
</style>
